package cn.px.service.sb.impl;

import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.enums.DataFilterTypeEnum;
import cn.px.common.model.UserInfo;
import cn.px.common.util.BigDecimalUtil;
import cn.px.common.util.ListUtils;
import cn.px.common.util.SecurityUtils;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.sb.SbStoreCheckJobDTO;
import cn.px.dao.entity.sb.SbStoreCheckJob;
import cn.px.dao.entity.sb.SbStoreCheckPlan;
import cn.px.dao.enums.CheckJobStatusEnum;
import cn.px.dao.enums.StoreCheckJobStatusEnum;
import cn.px.dao.enums.StoreCheckPlanStatusEnum;
import cn.px.dao.mapper.sb.SbStoreCheckJobMapper;
import cn.px.dao.mapper.sb.SbStoreCheckPlanMapper;
import cn.px.dao.vo.query.sb.SbStoreCheckJobVO;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.sb.SbStoreCheckJobService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 点检记录 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("sbStoreCheckJobService")
public class SbStoreCheckJobServiceImpl extends BaseServiceImpl<SbStoreCheckJobMapper, SbStoreCheckJob, SbStoreCheckJobDTO> implements SbStoreCheckJobService {
    private SbStoreCheckPlanMapper storeCheckPlanMapper;
    @Override
    public int batchDelete(List<String> ids) {
        Weekend<SbStoreCheckJob> weekend = new Weekend<>(SbStoreCheckJob.class);
        WeekendCriteria<SbStoreCheckJob, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andIn(SbStoreCheckJob::getId, ids);
        mapper.deleteByExample(weekend);
        return 1;
    }

    @Override
    public AbstractPageResultBean<SbStoreCheckJobVO> selectPageList(SbStoreCheckJobDTO model, int pageNum, int pageSize) {
        if (model.getFilter() != null && DataFilterTypeEnum.SELF.getValue() == model.getFilter().intValue()) {
            UserInfo userInfo = SecurityUtils.getUserInfo();
            model.setCheckUserId(userInfo.getUserId());
        }
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectList(model));
    }

    @Override
    public AbstractPageResultBean<SbStoreCheckJob> selectPageInfo(SbStoreCheckJobDTO model, int pageNum, int pageSize) {
        if (model.getFilter() != null && DataFilterTypeEnum.SELF.getValue() == model.getFilter().intValue()) {
            UserInfo userInfo = SecurityUtils.getUserInfo();
            model.setCheckUserId(userInfo.getUserId());
        }
        PageHelper.startPage(pageNum, pageSize);
        AbstractPageResultBean<SbStoreCheckJob> pageInfo = new MyPage(mapper.selectList(model));
        return pageInfo;
    }

    @Override
    public List<SbStoreCheckJobVO> selectList(SbStoreCheckJobDTO model) {
        if (model.getFilter() != null && DataFilterTypeEnum.SELF.getValue() == model.getFilter().intValue()) {
            UserInfo userInfo = SecurityUtils.getUserInfo();
            model.setCheckUserId(userInfo.getUserId());
        }
        return mapper.selectList(model);
    }

    @Override
    public void checkJobStatus() {
        // 1.查询状态为未执行和执行中的任务
        Weekend<SbStoreCheckJob> weekend = new Weekend<>(SbStoreCheckJob.class);
        Integer[] status = {1, 2};
        weekend.weekendCriteria().andIn(SbStoreCheckJob::getStatus, Arrays.asList(status));
        List<SbStoreCheckJob> checkJobs = mapper.selectByExample(weekend);
        // 2.判断当前时间是否大于结束时间是则设置状态未已过期
        LocalDateTime now = LocalDateTime.now();
        checkJobs.forEach(job -> {
            LocalDateTime endTime = job.getEndTime();
            if (now.isAfter(endTime)) {
                // job.setStatus(CheckJobStatusEnum.OUT_OF_DATE.getValue());
                //mapper.updateByPrimaryKeySelective(job);
            }
        });
    }

    @Override
    public SbStoreCheckJobVO getDetail(Object id) {
        return mapper.selectDetail(id);
    }

    @Override
    public int finishJob(SbStoreCheckJobDTO dto) {
        LocalDateTime now = LocalDateTime.now();
        SbStoreCheckJob checkJob = mapper.selectByPrimaryKey(dto.getId());
        checkJob.setStatus(StoreCheckJobStatusEnum.FINISHED.getValue());
        UserInfo userInfo = SecurityUtils.getUser().getUserInfo();
        checkJob.setUpdateTime(now);
        checkJob.setUpdateUserId(userInfo.getUserId());
        checkJob.setUpdateUserName(userInfo.getUsername());
        checkJob.setFeedback(dto.getFeedback());
        checkJob.setEndTime(now);
        checkJob.setRealNum(dto.getRealNum());
        checkJob.setRemark(dto.getRemark());
        // 正常
        if(dto.getRealNum().compareTo(dto.getCheckNum())==0){
            checkJob.setProfit(0);
            checkJob.setProfitNum(new BigDecimal(0));
        }
        // 盘盈
        if(dto.getRealNum().compareTo(dto.getCheckNum())>0){
            checkJob.setProfit(2);
            checkJob.setProfitNum(BigDecimalUtil.sub(dto.getRealNum(),dto.getCheckNum()));
        }
        // 盘亏
        if(dto.getRealNum().compareTo(dto.getCheckNum())<0){
            checkJob.setProfit(1);
            checkJob.setProfitNum(BigDecimalUtil.sub(dto.getCheckNum(),dto.getRealNum()));
        }
        mapper.updateByPrimaryKeySelective(checkJob);

        // 检查是否对应的计划的所有任务都执行完毕了
        SbStoreCheckJob job = new SbStoreCheckJob();
        job.setPlanId(checkJob.getPlanId());
        job.setStatus(StoreCheckJobStatusEnum.EXECUTING.getValue());
        int count = mapper.selectCount(job);
        if(count == 0){
            SbStoreCheckPlan plan = storeCheckPlanMapper.selectByPrimaryKey(checkJob.getPlanId());
            plan.setStatus(StoreCheckPlanStatusEnum.FINISHED.getValue());
            storeCheckPlanMapper.updateByPrimaryKey(plan);
            return 0;
        }else{
            return 1;
        }
    }

    @Override
    public int countUserTask(String userId, Integer type) {
        Weekend<SbStoreCheckJob> weekend = new Weekend<>(SbStoreCheckJob.class);
        WeekendCriteria<SbStoreCheckJob, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andEqualTo(SbStoreCheckJob::getCheckUserId, userId);
        List<Integer> statusList = ListUtils.newArrayList(CheckJobStatusEnum.NOT_EXECUTE.getValue(),
                CheckJobStatusEnum.EXECUTING.getValue());
        weekendCriteria.andIn(SbStoreCheckJob::getStatus, statusList);
        return mapper.selectCountByExample(weekend);
    }
}
